package com.timschimandle.getitdone;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RadioGroup;

public class GeneralListFragment extends ListFragment {
	
	OnItemSelectedListener mListener;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		View v = inflater.inflate(R.layout.general_item_list, container,false);
		
		Bundle bundle = this.getArguments();
		ArrayList<String> labels = new ArrayList<String>();
		labels.add("New");
		
		if (bundle != null) {		
			
			if (bundle.getSerializable("tasks") != null) {
				
				//add a phony task to hold the new option in the list.
				Task t = new Task(Long.valueOf(-1),"New",0,0,0,Long.valueOf(-1),1);
				
				@SuppressWarnings("unchecked")
				ArrayList<Task> tl = ((ArrayList<Task>) bundle.getSerializable("tasks"));
				tl.add(0,t);
				
				TaskAdapter adapter = new TaskAdapter(getActivity(), R.layout.task_list_row, tl);
				setListAdapter(adapter);
				
				
			} else if (bundle.getSerializable("people") != null) {
				
				//phony person to hold the new position
				Person p = new Person(Long.valueOf(-1),"New","","","");
				
				@SuppressWarnings("unchecked")
				ArrayList<Person> pl = (ArrayList<Person>) bundle.getSerializable("people");
				pl.add(0,p);
				
				PersonAdapter adapter = new PersonAdapter(getActivity(), R.layout.person_list_row, pl);
				setListAdapter(adapter);
				
			} else if (bundle.getSerializable("task_list") != null) {
				//get task list array
			}
		}
		
		return v;
		
	}

	public interface OnItemSelectedListener {
		public void onItemSelectedListener(Long id);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnItemSelectedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnItemSelectedListener in ToDoListActivity");
		}
	}
	
	public void onListItemClick(ListView l, View v, int position, long id) {
		//need to find what radio button is pressed and convert the object to its designated
		RadioGroup rg = (RadioGroup) getActivity().findViewById(R.id.radio_data);
		
		if (rg.getCheckedRadioButtonId() == R.id.task_list_button) {
			//get task list item to put in the other fragment
		} else if (rg.getCheckedRadioButtonId() == R.id.tasks) {
			Task t = (Task) l.getItemAtPosition(position);
			mListener.onItemSelectedListener(t.getId());
		} else if (rg.getCheckedRadioButtonId() == R.id.people) {
			Person p = (Person) l.getItemAtPosition(position);
			mListener.onItemSelectedListener(p.getID());
		}
	}
}
